/**
 * Moonshot AI 连接测试脚本
 * 用于验证API密钥和连接是否正常
 */

// 测试配置
const MOONSHOT_CONFIG = {
  baseURL: 'https://api.moonshot.cn/v1',
  apiKey: 'sk-9m78YQZh9aH9J08xL3mEvvHZEJy8q0Zo0Ds75SZTdihRvnnz',
  timeout: 30000
}

// 颜色输出
const colors = {
  reset: '\x1b[0m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  cyan: '\x1b[36m'
}

function log(message, color = 'reset') {
  if (typeof window === 'undefined') {
    console.log(`${colors[color]}${message}${colors.reset}`)
  } else {
    console.log(message)
  }
}

// Moonshot AI 测试类
class MoonshotTester {
  constructor(config) {
    this.config = config
    this.results = {
      passed: 0,
      failed: 0,
      total: 0
    }
  }

  // HTTP请求方法
  async request(endpoint, data = null, method = 'POST') {
    const url = `${this.config.baseURL}${endpoint}`
    
    const options = {
      method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.config.apiKey}`
      }
    }

    if (data && method !== 'GET') {
      options.body = JSON.stringify(data)
    }

    try {
      const response = await fetch(url, options)
      const result = await response.json()
      
      return {
        success: response.ok,
        status: response.status,
        data: result
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 运行测试
  async runTest(testName, testFunction) {
    this.results.total++
    
    try {
      log(`\n🧪 测试: ${testName}`, 'cyan')
      
      const startTime = Date.now()
      await testFunction()
      const endTime = Date.now()
      
      this.results.passed++
      log(`✅ 通过 (${endTime - startTime}ms)`, 'green')
      
    } catch (error) {
      this.results.failed++
      log(`❌ 失败: ${error.message}`, 'red')
    }
  }

  // 测试1: 获取模型列表
  async testGetModels() {
    await this.runTest('获取Moonshot模型列表', async () => {
      const response = await this.request('/models', null, 'GET')
      
      if (!response.success) {
        throw new Error(`获取模型列表失败: ${response.status}`)
      }
      
      if (!response.data.data || !Array.isArray(response.data.data)) {
        throw new Error('模型列表格式错误')
      }
      
      log(`  可用模型数量: ${response.data.data.length}`, 'blue')
      response.data.data.forEach(model => {
        log(`    - ${model.id}`, 'blue')
      })
    })
  }

  // 测试2: 基础聊天功能
  async testBasicChat() {
    await this.runTest('基础聊天功能', async () => {
      const testMessage = '你好，请简单介绍一下自己'
      
      const response = await this.request('/chat/completions', {
        model: 'moonshot-v1-8k',
        messages: [
          { role: 'user', content: testMessage }
        ],
        temperature: 0.3,
        max_tokens: 100
      })
      
      if (!response.success) {
        throw new Error(`聊天请求失败: ${response.status} - ${response.data?.error?.message || '未知错误'}`)
      }
      
      if (!response.data.choices || !response.data.choices[0]?.message?.content) {
        throw new Error('聊天响应格式错误')
      }
      
      const aiResponse = response.data.choices[0].message.content
      log(`  用户: ${testMessage}`, 'yellow')
      log(`  Moonshot: ${aiResponse.substring(0, 100)}...`, 'blue')
      
      if (response.data.usage) {
        log(`  Token使用: ${response.data.usage.total_tokens}`, 'blue')
      }
    })
  }

  // 测试3: 流式聊天功能
  async testStreamChat() {
    await this.runTest('流式聊天功能', async () => {
      return new Promise((resolve, reject) => {
        const testMessage = '请用一句话介绍人工智能'
        let receivedContent = ''
        let isCompleted = false
        
        fetch(`${this.config.baseURL}/chat/completions`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.config.apiKey}`
          },
          body: JSON.stringify({
            model: 'moonshot-v1-8k',
            messages: [
              { role: 'user', content: testMessage }
            ],
            temperature: 0.3,
            max_tokens: 100,
            stream: true
          })
        })
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP ${response.status}`)
          }
          
          const reader = response.body.getReader()
          const decoder = new TextDecoder()
          
          function readStream() {
            reader.read().then(({ done, value }) => {
              if (done) {
                if (receivedContent.length > 0) {
                  log(`  流式响应长度: ${receivedContent.length}`, 'blue')
                  resolve()
                } else {
                  reject(new Error('未收到有效内容'))
                }
                return
              }
              
              const chunk = decoder.decode(value, { stream: true })
              const lines = chunk.split('\n')
              
              for (const line of lines) {
                if (line.startsWith('data: ')) {
                  const data = line.slice(6).trim()
                  
                  if (data === '[DONE]') {
                    isCompleted = true
                    if (receivedContent.length > 0) {
                      log(`  流式响应长度: ${receivedContent.length}`, 'blue')
                      resolve()
                    } else {
                      reject(new Error('未收到有效内容'))
                    }
                    return
                  }
                  
                  try {
                    const parsed = JSON.parse(data)
                    const content = parsed.choices?.[0]?.delta?.content
                    if (content) {
                      receivedContent += content
                    }
                  } catch (e) {
                    // 忽略解析错误
                  }
                }
              }
              
              readStream()
            }).catch(reject)
          }
          
          readStream()
        })
        .catch(reject)
        
        // 超时处理
        setTimeout(() => {
          if (!isCompleted) {
            reject(new Error('流式响应超时'))
          }
        }, this.config.timeout)
      })
    })
  }

  // 测试4: 代码生成功能
  async testCodeGeneration() {
    await this.runTest('代码生成功能', async () => {
      const codePrompt = '请用JavaScript写一个简单的冒泡排序函数'
      
      const response = await this.request('/chat/completions', {
        model: 'moonshot-v1-8k',
        messages: [
          { 
            role: 'user', 
            content: `${codePrompt}\n\n要求：只返回代码，不需要额外说明。` 
          }
        ],
        temperature: 0.2,
        max_tokens: 500
      })
      
      if (!response.success) {
        throw new Error(`代码生成失败: ${response.status}`)
      }
      
      const generatedCode = response.data.choices[0].message.content
      
      if (!generatedCode.includes('function') && !generatedCode.includes('=>')) {
        throw new Error('生成的内容不像是JavaScript代码')
      }
      
      log(`  代码长度: ${generatedCode.length} 字符`, 'blue')
    })
  }

  // 测试5: 错误处理
  async testErrorHandling() {
    await this.runTest('错误处理机制', async () => {
      // 测试无效模型
      const response = await this.request('/chat/completions', {
        model: 'invalid-model-name',
        messages: [
          { role: 'user', content: '测试' }
        ]
      })
      
      if (response.success) {
        throw new Error('无效模型应该返回错误')
      }
      
      if (response.status !== 400 && response.status !== 404) {
        throw new Error(`期望400或404错误，但收到: ${response.status}`)
      }
      
      log(`  错误处理正常 (${response.status})`, 'blue')
    })
  }

  // 运行所有测试
  async runAllTests() {
    log('🌙 开始Moonshot AI连接测试', 'cyan')
    log(`📍 API地址: ${this.config.baseURL}`, 'cyan')
    log(`🔑 API密钥: ${this.config.apiKey.substring(0, 20)}...`, 'cyan')
    
    await this.testGetModels()
    await this.testBasicChat()
    await this.testStreamChat()
    await this.testCodeGeneration()
    await this.testErrorHandling()
    
    this.printResults()
  }

  // 输出测试结果
  printResults() {
    log('\n📊 测试结果汇总', 'cyan')
    log('=' * 50, 'cyan')
    
    const passRate = (this.results.passed / this.results.total * 100).toFixed(1)
    
    log(`总测试数: ${this.results.total}`, 'blue')
    log(`通过: ${this.results.passed}`, 'green')
    log(`失败: ${this.results.failed}`, 'red')
    log(`通过率: ${passRate}%`, passRate >= 80 ? 'green' : 'red')
    
    if (this.results.failed === 0) {
      log('\n🎉 所有测试通过！Moonshot AI连接成功！', 'green')
      log('\n🚀 现在你可以:', 'cyan')
      log('1. 访问 http://localhost:9990/#/moonshot-demo', 'blue')
      log('2. 在项目中使用 MoonshotChat 组件', 'blue')
      log('3. 调用 moonshotService 进行AI对话', 'blue')
    } else {
      log('\n⚠️  部分测试失败，请检查:', 'yellow')
      log('1. API密钥是否正确', 'blue')
      log('2. 网络连接是否正常', 'blue')
      log('3. Moonshot服务是否可用', 'blue')
    }
  }
}

// 浏览器环境
if (typeof window !== 'undefined') {
  window.MoonshotTester = MoonshotTester
  window.runMoonshotTests = () => {
    const tester = new MoonshotTester(MOONSHOT_CONFIG)
    return tester.runAllTests()
  }
  
  console.log('🌙 Moonshot AI 测试工具已加载')
  console.log('请在控制台运行: runMoonshotTests()')
  
} else {
  // Node.js环境
  const fetch = require('node-fetch')
  global.fetch = fetch
  
  const tester = new MoonshotTester(MOONSHOT_CONFIG)
  tester.runAllTests().catch(console.error)
}

// 导出
if (typeof module !== 'undefined' && module.exports) {
  module.exports = MoonshotTester
}
